#!/bin/bash

# filepath: /d:/shutdown-manager/deploy.sh

# 定义变量
APP_DIR="/opt/shutdown-manager"
CONFIG_PATH="/etc/shutdown-schedules.json"
CRON_PATH="/etc/crontab"
LOG_PATH="/var/log/shutdown-manager.log"
NODE_VERSION="14"

echo "开始部署 shutdown-manager..."

# 检查是否以 root 用户运行
if [ "$EUID" -ne 0 ]; then
  echo "请以 root 用户运行此脚本。"
  exit 1
fi

# 更新系统并安装必要的软件包
echo "更新系统并安装必要的软件包..."
apt update && apt upgrade -y
apt install -y nodejs npm git sed

# 检查 Node.js 版本
echo "检查 Node.js 版本..."
if ! node -v | grep -q "^v$NODE_VERSION"; then
  echo "安装 Node.js $NODE_VERSION..."
  curl -fsSL https://deb.nodesource.com/setup_$NODE_VERSION.x | bash -
  apt install -y nodejs
fi

# 克隆项目到目标目录
echo "克隆项目到 $APP_DIR..."
if [ ! -d "$APP_DIR" ]; then
  git clone https://gitee.com/wlq93571/shutdown-manager.git "$APP_DIR"
else
  echo "项目目录已存在，跳过克隆。"
fi

# 进入项目目录
cd "$APP_DIR" || exit

# 安装项目依赖
echo "安装项目依赖..."
npm install

# 配置文件和日志文件
echo "配置文件和日志文件..."
if [ ! -f "$CONFIG_PATH" ]; then
  echo "[]" > "$CONFIG_PATH"
  echo "创建配置文件: $CONFIG_PATH"
fi

if [ ! -f "$LOG_PATH" ]; then
  touch "$LOG_PATH"
  echo "创建日志文件: $LOG_PATH"
fi

# 确保 crontab 文件存在
if [ ! -f "$CRON_PATH" ]; then
  touch "$CRON_PATH"
  echo "创建 crontab 文件: $CRON_PATH"
fi

# 设置文件权限
echo "设置文件权限..."
chown root:root "$CONFIG_PATH" "$LOG_PATH" "$CRON_PATH"
chmod 644 "$CONFIG_PATH" "$LOG_PATH" "$CRON_PATH"

# 创建 systemd 服务文件
echo "创建 systemd 服务文件..."
SERVICE_FILE="/etc/systemd/system/shutdown-manager.service"
cat > "$SERVICE_FILE" <<EOL
[Unit]
Description=Shutdown Manager Service
After=network.target

[Service]
ExecStart=/usr/bin/node $APP_DIR/server.js
WorkingDirectory=$APP_DIR
Restart=always
User=root
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOL

# 重新加载 systemd 并启动服务
echo "启动服务..."
systemctl daemon-reload
systemctl enable shutdown-manager
systemctl start shutdown-manager

# 检查服务状态
echo "检查服务状态...."
systemctl status shutdown-manager --no-pager

echo "部署完成！服务已启动: http://localhost:3000"